package com.mondo.financialwallet.presentation.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.example.common.ui.AbsNetworkStateActivity;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.ClearProductDetailsEntity;
import com.mondo.financialwallet.presentation.model.HoldProduct;
import com.mondo.financialwallet.presentation.event.RequestHoldProductEvent;
import com.mondo.financialwallet.presentation.ui.dialog.TipsDialog;
import com.mondo.financialwallet.presentation.ui.dialog.VerificationPasswordDialog;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.DateUtils;
import com.mondo.financialwallet.presentation.utils.LocalConfigStorage;
import com.mondo.financialwallet.presentation.utils.Toasts;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;

/**
 * 清算产品
 *
 * TODO 有中文
 */
public class ProductLiquidationActivity extends AbsNetworkStateActivity {

    private static final String EXTRA_PRODUCT = "PRODUCT";

    public static void launch(Context context, HoldProduct product) {
        context.startActivity(
                new Intent(context, ProductLiquidationActivity.class)
                        .putExtra(EXTRA_PRODUCT, product)
        );
    }

    @Bind(R.id.name_text_view) TextView mNameTextView;
    @Bind(R.id.investment_period_text) TextView mInvestmentPeriodText;
    @Bind(R.id.transaction_date_text) TextView mTransactionDateText;
    @Bind(R.id.total_product_text) TextView mTotalProductText;
    @Bind(R.id.subscription_fee_text) TextView mSubscriptionFeeText;
    @Bind(R.id.accumulative_income_text) TextView mAccumulativeIncomeText;
    @Bind(R.id.management_fee_text) TextView mManagementFeeText;
    @Bind(R.id.liquidated_damages_text) TextView mLiquidatedDamagesText;
    @Bind(R.id.arrival_time_tips_text) TextView mArrivalTimeTipsText;
    @Bind(R.id.amount_receivable_text) TextView mAmountReceivableText;
    @Bind(R.id.liquidation_button) View mLiquidationButton;

    private HoldProduct mProduct;

    @Override
    public int getTitleLayoutRes() {
        return R.layout.include_default_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_product_liquidation;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_liquidation);

        // 持有产品
        mProduct = (HoldProduct) getIntent().getSerializableExtra(EXTRA_PRODUCT);

        // 清算
        mLiquidationButton.setOnClickListener(v -> liquidationProduct());

        // 清算产品详情
        requestClearProductDetails();
    }

    private void liquidationProduct() {
        if (LocalConfigStorage.get().isBindGoogleValidator()) {
            // 弹出验证对话框
            VerificationPasswordDialog.googleValidator().setPositive(dialog -> {
                if(TextUtils.isEmpty(dialog.getText())){
                    dialog.setErrorMessage(getString(R.string.message_please_enter_your_password));
                    return;
                }

                requestClearProduct(dialog, dialog.getText());
            }).setActionListener(v -> {
                BindAndEditGoogleValidatorActivity.launchEdit(this);
            }).build(this).show();

        } else {
            TipsDialog.warning(this)
                    .build(R.string.dialog_title_unbound_google_authenticator,
                            R.string.dialog_message_bind_google_authenticator_clear,
                            v -> BindAndEditGoogleValidatorActivity.launchBind(this))
                    .show();
        }
    }

    private void requestClearProductDetails(){
        loadingNetwork();

        DataRepository.get().clearProductDetails(mProduct.getOrderNumber(), result -> {
            if (result.isSuccess()) {
                successNetwork();
                ClearProductDetailsEntity.DataBean data = result.getData();

                // 产品信息
                mNameTextView.setText(mProduct.getName());
                mInvestmentPeriodText.setText("投资期限："+mProduct.getMinimumDay());
                mTransactionDateText.setText("交易时间：" + data.getPay_at());

                // 清算明细
                mTotalProductText.setText("$" + data.getTotal_money());    // 产品总额
                mSubscriptionFeeText.setText("$" + data.getSubscribe_fee());// 认购费用
                mAccumulativeIncomeText.setText("$" + data.getProfit());    // 累计收益
                mManagementFeeText.setText("-$" + data.getManage_fee());     // 管理费用
                mLiquidatedDamagesText.setText("-$" + data.getBreach_money()); // 违约金
                mArrivalTimeTipsText.setText(Html.fromHtml(
                        String.format(getString(R.string.text_arrival_time_tips),
                                String.valueOf(data.getTransfer_day()),
                                DateUtils.timestampToTimeStyle_4(DateUtils.designationDayTimestamp(data.getTransfer_day())))));

                // 应收金额
                mAmountReceivableText.setText("$" + data.getAvailable_fee());
            } else {
                errorNetwork(result.getMsg());
            }
        });
    }

    private void requestClearProduct(VerificationPasswordDialog dialog, String code) {
        DataRepository.get().clearProduct(mProduct.getOrderNumber(), code, result -> {
            if (result.isSuccess()) {
                dialog.dismiss();
                Toasts.success(R.string.message_clear_success);
                EventBus.getDefault().post(new RequestHoldProductEvent());
                startActivityAndFinish(new Intent(this, MainActivity.class));
            } else {
                dialog.setErrorMessage(result.getMsg());
            }
        });
    }

    @Override
    public void onAnewRequest() {
        requestClearProductDetails();
    }
}
